package com.hj.util;


import cn.hutool.core.codec.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author hj
 * @Description BASE64 加解密
 */
@Component
public class CypherUtil {

    @Value("${sys.salt}")
    private String salt;

    /**
     * 加密
     *
     * @param content 加密的内容
     * @return 加密后的结果
     */
    public String aesEncode(String content) {
        try {
            Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
            byte[] byteEncode = content.getBytes(StandardCharsets.UTF_8);
            byte[] byteAes = cipher.doFinal(byteEncode);
            return Base64.encode(byteAes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
                IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Cipher getCipher(Integer mode) throws NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException {

        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
        random.setSeed(salt.getBytes());
        /*new SecureRandom(salt.getBytes())*/
        keygen.init(128, random);
        SecretKey originalKey = keygen.generateKey();
        byte[] raw = originalKey.getEncoded();
        SecretKey key = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(mode, key);
        return cipher;
    }

    /**
     * 解密
     *
     * @param content 解密的内容
     * @return 明文
     */
    public String aesDecode(String content) {
        try {
            Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
            byte[] byteContent = Base64.decode(content);
            byte[] byteDecode = cipher.doFinal(byteContent);
            return new String(byteDecode, StandardCharsets.UTF_8);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
                | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }


}
